
const request = require('../../utils/request')

Page({
  data: {
    kw: '',
    list: [],
    loading: false,
    page: 1,
    page_size: 20,
    finished: false
  },

  onInput(e) {
    this.setData({ kw: e.detail.value })
  },

  async onSearch() {
    const { kw } = this.data
    if (!kw.trim()) {
      wx.showToast({ title: '请输入关键字', icon: 'none' })
      return
    }
    this.setData({ page: 1, list: [], finished: false })
    await this.fetchList()
  },

  async fetchList() {
    if (this.data.finished) return
    this.setData({ loading: true })
    const { kw, page, page_size } = this.data
    try {
      const res = await request.get('/api/v1/drugs/search', {
        kw, page, page_size,
      })
      const { list, meta } = res.data
      this.setData({
        list: [...this.data.list, ...list],
        loading: false,
        finished: this.data.page * page_size >= meta.total
      })
    } catch (err) {
      this.setData({ loading: false })
    }
  },

  toDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({ url: `/pages/detail/detail?id=${id}` })
  },

  // 下拉触底加载
  onReachBottom() {
    if (this.data.finished) return
    this.setData({ page: this.data.page + 1 }, () => this.fetchList())
  }
})